package com.myhome.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.myhome.service.SysPrivilegeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.myhome.domain.SysMenu;
import com.myhome.mapper.SysMenuMapper;
import com.myhome.service.SysMenuService;
/**
*@Author QYiXin 
* @Date 2021 10 09 12 58
**/
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService{
    @Autowired
    SysMenuMapper sysMenuMapper;
    @Autowired
    SysPrivilegeService sysPrivilegeService;
    @Override
    public List<SysMenu> getMenusByUserId(Long userId) {
        return sysMenuMapper.getMenusByUserId(userId);
    }

    @Override
    public List<SysMenu> getRolePrivileges(Long roleId) {
        List<SysMenu> listMenus = this.list();
        if (CollectionUtil.isEmpty(listMenus)) {
            return Collections.emptyList();
        }
        List<SysMenu> rootMenus = listMenus.stream().filter(menu -> menu.getParentId() == null).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(rootMenus)) {
            return Collections.emptyList();
        }
        List<SysMenu> allChildrenMenus = new ArrayList<>();
        for (SysMenu rootMenu : rootMenus) {
            allChildrenMenus.addAll(getOneRootMenusChildren(rootMenu.getId(), listMenus, roleId));
        }
        return allChildrenMenus;
    }

    private List<SysMenu> getOneRootMenusChildren(Long parentId, List<SysMenu> listMenus, Long roleId) {
        List<SysMenu> children = new ArrayList<>();
        for (SysMenu listMenu : listMenus) {
            if (Objects.equals(listMenu.getParentId(), parentId)) {
                children.add(listMenu);
                listMenu.setChilds(getOneRootMenusChildren(listMenu.getId(),listMenus,roleId));
                listMenu.setPrivileges(sysPrivilegeService.getPrivileges(roleId,listMenu.getId()));
            }
        }
        return children;
    }
}
